#include "led.h"
#include "qumi_config.h"


#define ONE_LED   (1)

  
static bool g_blink_state = TRUE;

void LED_Init(void)
{

  TIM2_TimeBaseInit(TIM2_PRESCALER_256, TIM2_TOTAL_LEN);
  //setup TIM2 CH2 UPDATE interrupt 
  TIM2_OC3Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE, TIM2_CCR3_Val, TIM2_OCPOLARITY_HIGH);
  /*TIM2_OC2PreloadConfig(ENABLE);*/
  /*TIM2_ITConfig(TIM2_IT_UPDATE, ENABLE);*/
}

void LED_Start(FunctionalState state)
{
  TIM2_Cmd(state);
}

void LED_Blink(bool enable)
{
  uint16_t val = 0;

  if (g_blink_state == enable)
  {
    return;
  }

  if (enable)
  {
    //blink. set compare to half of TIM2_TOTAL_LEN
    val = TIM2_TOTAL_LEN / 2;  
  }
  else
  {
    //const. set compare to TIM2_TOTAL_LEN
    val = TIM2_TOTAL_LEN;
  }

  TIM2_SetCompare3(val);
  g_blink_state = enable;
}

void LED_Task(void)
{
  uint16_t data = ADC1_GetBufferValue(BATTERY_CH);

  if (data < BATTERY_THRESHOLD)
  {
    LED_Blink(TRUE);
  }
  else
  {
    LED_Blink(FALSE);
  }
}
